package com.minsf.springbootinit.cas;

import org.checkerframework.checker.units.qual.A;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description 自定义自旋锁
 * @Author minify
 * @Date 2024/1/4 0:25
 * @Project oj-backend
 */
public class SpinLockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        System.out.println(Thread.currentThread().getName()+" come in!");
        while (!atomicReference.compareAndSet(null, Thread.currentThread())) {

        }
        System.out.println(Thread.currentThread().getName()+" lock over!");
    }

    public void unLock() {
        System.out.println(Thread.currentThread().getName()+" come unLock!");
        atomicReference.set(null);
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        Thread t1 = new Thread(() -> {
            spinLockDemo.lock();
            try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) {throw new RuntimeException(e);}
            spinLockDemo.unLock();

        }, "t1");
        t1.start();

        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        Thread t2 = new Thread(() -> {
            spinLockDemo.lock();
            spinLockDemo.unLock();
        }, "t2");
        t2.start();
    }
}